#include <iostream>
#include <string>
#include <mysql/mysql.h>

using namespace std;

void query()
{
    // 1. 初始化数据库连接
    MYSQL *con = mysql_init(NULL);

    // 2. 连接数据库时需要判断是否连接成功，
    mysql_real_connect(con, "127.0.0.1", "li", "123456", "tallyBook", 0, NULL, CLIENT_MULTI_STATEMENTS);

    // 3. 查询数据
    auto search_res = mysql_query(con, "select * from user;");

    // 4. 获取查询数据
    auto result = mysql_store_result(con);
    int col = mysql_num_fields(result);//获取列数
    int row = mysql_num_rows(result);//获取行数

    for(int i = 0; i < row; i++) {
        auto info = mysql_fetch_row(result);//获取一行的信息
        cout<<"id: "<< info[0] << " name: "<< info[1] << " passwd: "<< info[2] << endl;
    }

    // 5. 关闭数据连接
    mysql_close(con);
}

void insert()
{
    MYSQL *con = mysql_init(NULL);
    // 连接数据库时需要判断是否连接成功，
    mysql_real_connect(con, "127.0.0.1", "li", "123456", "tallyBook", 0, NULL, CLIENT_MULTI_STATEMENTS);
    const char* sql = "insert into user values('1002', 'devi', '123456');";
    int ret = mysql_query(con, sql);
    if(ret == 0) {
        cout << "msg = 插入数据成功， sql = "<< sql << endl;
    }
    else {
        cout << "msg = 插入数据失败， sql = "<< sql << endl;
    }

    mysql_close(con);
}

int main(int argc, char* argv[])
{
    insert();
    query();
    return 0;
}
